import Base from "./Base"
import Circle from "./Circle"
import { V2Util, IPos, ISize } from "../util/V2Util"

const v2 = V2Util

export default class Rect extends Base {

    /** 矩形的四个顶点 右上逆时针排列*/
    get vertexs() {
        let vs: IPos[] = []
        for (let i = 0; i < 4; i++)
            vs.push(this.getVertex(<any>i))
        return vs
    }

    setSize(size: ISize) {
        this.w = size.w
        this.h = size.h
        return this
    }

    /** 获取矩形在某象限的顶点 0:右上*/
    getVertex(quad: 0 | 1 | 2 | 3): IPos {
        switch (quad) {
            case 0:
                return { x: this.x + this.w * 0.5, y: this.y + this.h * 0.5 }
            case 1:
                return { x: this.x - this.w * 0.5, y: this.y + this.h * 0.5 }
            case 2:
                return { x: this.x - this.w * 0.5, y: this.y - this.h * 0.5 }
            case 3:
                return { x: this.x + this.w * 0.5, y: this.y - this.h * 0.5 }
        }
    }

    /** 复制 */
    cp() {
        return new Rect(this)
    }

    /** 判断是否与目标碰撞 */
    collide(obj: Base): boolean {
        return obj instanceof Circle ? Rect.collideCircle(this, obj) :
            obj instanceof Rect ? Rect.collideRect(this, obj) : false
    }

    /** 判断是否被目标包含 */
    in(obj: Base): boolean {
        return obj instanceof Circle ? Rect.inCircle(this, obj) :
            obj instanceof Rect ? Rect.inRect(this, obj) : false
    }

    /** 判断矩形是否与目标圆形碰撞 */
    static collideCircle(rect: Rect, circle: Circle) {
        return Circle.collideRect(circle, rect)
    }

    /** 判断矩形是否与目标矩形碰撞 */
    static collideRect(r1: Rect, r2: Rect) {
        //得到两个矩形的第三象限顶点
        let v1 = r1.getVertex(2)
        let v2 = r2.getVertex(2)
        return v1.x < v2.x + r2.w && v1.y < v2.y + r2.h && v1.x + r1.w > v2.x && v1.y + r1.h > v2.y
    }

    /** 判断矩形是否被目标圆形包含 */
    static inCircle(rect: Rect, circle: Circle) {
        //暂未用到
        return false
    }

    /** 判断矩形是否被目标矩形包含 */
    static inRect(r1: Rect, r2: Rect) {
        //r1转换到r2右上象限
        let rect = r1.cp().pos(v2.toFirstQuad(r1, r2))
        //r1在r2右上象限的右上、左下象限顶点
        let r1v1 = rect.getVertex(0)
        let r1v3 = rect.getVertex(2)
        //r2的右上、左下象限顶点
        let r2v1 = r2.getVertex(0)
        let r2v3 = r2.getVertex(2)
        return r1v1.x < r2v1.x && r1v1.y < r2v1.y &&
            r1v3.x > r2v3.x && r1v3.y > r2v3.y
    }

}